//==================================================================
/// sector_list.cpp
///
/// Created by Davide Pasca - 2009/10/5
/// See the file "license.txt" that comes with this project for
/// copyright info. 
//==================================================================

#include "stdafx.h"
#include "sector_list.h"

//==================================================================
SectorList::SectorList()
{
	_total_len	= 0;

	_read_pos	= 0;
	_read_cnt	= 0;
}

void SectorList::add( const SectorDef &def )
{
	Sector	*pSector = mSectors.grow();

	pSector->mpObj	= def.mpObj;
	pSector->len	= def.len;
	pSector->step	= def.step;
	pSector->offX	= def.offX;
	pSector->angle	= def.angle;
	pSector->vangle	= def.vangle;
	pSector->lanes	= def.lanes;

	if ( mSectors.size() > 1 )
	{
		size_t prev = mSectors.size() - 2;
		pSector->basePos = mSectors[prev].basePos + mSectors[prev].len;
	}
	else
		pSector->basePos = 0;

	_total_len += def.len;
}

int SectorList::get_len( int sector )
{
	return mSectors[sector].len;
}

int SectorList::get_base( int sector )
{
	return mSectors[sector].basePos;
}

const sprite *SectorList::get_object( int sector ) const
{
	return mSectors[sector].mpObj;
}

sprite *SectorList::get_object( int sector )
{
	return mSectors[sector].mpObj;
}

float SectorList::get_coe( int sector, int pos )
{
	int		base, len;

	base = mSectors[sector].basePos;
	len  = mSectors[sector].len;
	return (pos/100.0f - base) / (len != 0 ? len : 1);
}

bool SectorList::is_drawable( int sector, int pos ) const
{
	int	step;

	pos /= 100;

	step = mSectors[sector].step;
	if ( step == 0 )
		return false;

	--step;
	if ( (pos & step) == step )
		return true;

	return false;
}

bool SectorList::is_drawable2( int sector, int pos ) const
{
	int	step;

	pos /= 100;

	step = mSectors[sector].step;
	if ( step == 0 )
		return false;

	if ( (pos & step) == step )
		return true;

	return false;
}

//==================================================================
int SectorListIter::find_prev( int pos )
{
	if ( (*mpSectors).size() )
	{
		pos /= 100;
		for (int i=_from_sect; i >= 0; --i)
		{
			int pos1 = (*mpSectors)[i].basePos;
			int pos2 = pos1 + (*mpSectors)[i].len;
			if ( pos >= pos1 && pos < pos2 )
				return _from_sect = i;
		}
	}

	return -1;
}

//==================================================================
int SectorListIter::find_next( int pos )
{
	pos /= 100;
	for (int i=_from_sect; i < (int)(*mpSectors).size()-1; ++i)
	{
		int pos1 = (*mpSectors)[i].basePos;
		int pos2 = pos1 + (*mpSectors)[i].len;

		if ( pos >= pos1 && pos < pos2 )
			return _from_sect = i;
	}

	return -1;
}